package models

import (
	"CommonsProject/conf"
	"CommonsProject/models/generatorModel"
	"CommonsProject/models/systemModel"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
)

var Database *gorm.DB

// InitDatabase 初始化数据库
func InitDatabase(mysqlConfig conf.Mysql) {
	connectionURL := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		mysqlConfig.Username,
		mysqlConfig.Password,
		mysqlConfig.Host,
		mysqlConfig.Port,
		mysqlConfig.DbName)

	var err error
	Database, err = gorm.Open(mysql.Open(connectionURL), &gorm.Config{
		//SkipDefaultTransaction: false, //是否跳过事务，默认会创建事务为增删改
		//NamingStrategy: schema.NamingStrategy{
		//TablePrefix:  //表前缀
		//SingularTable: true, //是否为单表，如果为false的话，例如 user 就会变成 users
		//NoLowerCase: false, //是否不转换大写换为小写
		//},
		Logger: logger.Default.LogMode(logger.Info), //设置日志级别，所有日志都打印出来
	})

	if err != nil {
		log.Panicln("连接数据库失败：", err.Error())
	}

	//注册实体
	registerStruct()
}

// 注册实体
func registerStruct() {
	systemModel.RegisterSystemModel(Database)
	generatorModel.RegisterGeneratorModel(Database)
}
